/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Productos;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author alrojas
 */
public final class IPrincipal1 extends JFrame{

    private JLabel      buscarLab;
    private JTextField  buscarCam;
    private JTable      listaTab;
    private TableRowSorter<TableModel> clasificador;
    private JButton     agregarBut;
    private JButton     reabastecerBut;    
    private JButton     editarBut;
    private JButton     eliminarBut;    
    
    private JPanel panelp;
    private JLabel banner;
    
    public IPrincipal1(JFrame padre) throws HeadlessException {
        
        super("Productos");
        this.setLayout(new BorderLayout());
        
        inicializarComponentes();
        inicializarListeners(padre);
       
        this.pack();
        this.setVisible(true);
        this.setLocationRelativeTo(null);
        
        

    }
    
    public void inicializarComponentes(){
        
        panelp = new JPanel(new BorderLayout());
        banner = new JLabel(new ImageIcon("figuras/banner.jpg"));
        banner.setBorder(new TitledBorder(""));
        
        Font fNegrita = new Font("Arial",1,17);
        Font fRegular = new Font("Arial",0,17);
        
        JPanel filtroPanel = new JPanel(new FlowLayout());
        buscarLab = new JLabel("Buscar Producto (Alt + B)");
        buscarLab.setFont(fNegrita);
        buscarCam = new JTextField(40);
        buscarCam.setFont(fRegular);
        filtroPanel.add(buscarLab); filtroPanel.add(buscarCam);
        panelp.add(filtroPanel,BorderLayout.NORTH);
        
        JPanel botonesPanel = new JPanel(); 
        botonesPanel.setLayout(new BoxLayout(botonesPanel,BoxLayout.Y_AXIS)); 
        agregarBut = new JButton("Nuevo (Ctrl + N)",new ImageIcon("figuras/add80.png"));
        agregarBut.setHorizontalTextPosition(SwingConstants.CENTER);
        agregarBut.setVerticalTextPosition(SwingConstants.BOTTOM) ;
        agregarBut.setVerticalAlignment(SwingConstants.CENTER);
        botonesPanel.add(agregarBut);
        reabastecerBut = new JButton("Re-Abastecer",new ImageIcon("figuras/replenish80.png"));
        reabastecerBut.setHorizontalTextPosition(SwingConstants.CENTER);
        reabastecerBut.setVerticalTextPosition(SwingConstants.BOTTOM) ;
        reabastecerBut.setVerticalAlignment(SwingConstants.CENTER);
        //botonesPanel.add(reabastecerBut);
        editarBut = new JButton("Editar (Ctrl + D)",new ImageIcon("figuras/edit80.png"));
        editarBut.setHorizontalTextPosition(SwingConstants.CENTER);
        editarBut.setVerticalTextPosition(SwingConstants.BOTTOM) ;
        editarBut.setVerticalAlignment(SwingConstants.CENTER);
        botonesPanel.add(editarBut);
        eliminarBut = new JButton("Eliminar (Ctrl + E)",new ImageIcon("figuras/delete80.png"));
        eliminarBut.setHorizontalTextPosition(SwingConstants.CENTER);
        eliminarBut.setVerticalTextPosition(SwingConstants.BOTTOM) ;
        eliminarBut.setVerticalAlignment(SwingConstants.CENTER);
        botonesPanel.add(eliminarBut);
        panelp.add(botonesPanel,BorderLayout.EAST);
        
        Vector < String > columnNames = new Vector < String >(); 
        columnNames.add("Código"); 
        columnNames.add("N. Comercial"); 
        columnNames.add("N. Genérico"); 
        columnNames.add("Existencias"); 
        columnNames.add("Presentación"); 
        columnNames.add("Laboratorio");     
        columnNames.add("F. Vencimiento"); 
        columnNames.add("Dias Vencidos"); 
        
        Vector < Vector < String > > productos;
        try {
            productos = CProducto.dameTodo();
            DefaultTableModel modelo = new DefaultTableModel(productos,columnNames){
                
                @Override
                public boolean isCellEditable (int row, int column){
                    return false;
                }
            };
            
            DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
            renderer.setHorizontalAlignment(SwingConstants.CENTER);

            listaTab = new JTable(modelo);
            listaTab.getTableHeader().setFont(fNegrita);
            listaTab.setFont(fRegular);
            listaTab.setRowHeight(30);
            listaTab.getColumnModel().getColumn(0).setCellRenderer(renderer);
            listaTab.getColumnModel().getColumn(1).setCellRenderer(renderer);
            listaTab.getColumnModel().getColumn(2).setCellRenderer(renderer);
            listaTab.getColumnModel().getColumn(3).setCellRenderer(renderer);
            listaTab.getColumnModel().getColumn(4).setCellRenderer(renderer); 
            listaTab.getColumnModel().getColumn(5).setCellRenderer(renderer);
            listaTab.getColumnModel().getColumn(6).setCellRenderer(renderer);
            listaTab.getColumnModel().getColumn(7).setCellRenderer(renderer);
            
            ((DefaultTableCellRenderer)listaTab.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
            JScrollPane barras = new JScrollPane(listaTab);
            panelp.add(barras,BorderLayout.CENTER);
            
        } catch (SQLException ex) {
            Logger.getLogger(IPrincipal1.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(IPrincipal1.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        add(banner,BorderLayout.NORTH);
        add(panelp,BorderLayout.CENTER);
           
        
    }
    
    public void inicializarListeners(final JFrame padre){
        
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
            KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cerrar"); 
        getRootPane().getActionMap().put("Cerrar", new AbstractAction(){
            public void actionPerformed(ActionEvent e)
            {
                setVisible(false);
            }
        });  
        
        if (padre != null){
            
            listaTab.addMouseListener(new MouseAdapter(){
                public void mouseClicked(MouseEvent e){ 
                    if (e.getClickCount() == 2){
                        // Las siguientes lineas son un asco!, iuuuu!
                        final Ventas.IAgregar padreReal = (Ventas.IAgregar) padre;
                        if(!padreReal.yaEstaAgregado(Integer.parseInt(listaTab.getValueAt(listaTab.getSelectedRow(),0).toString()))){
                            padreReal.agregarProducto(Integer.parseInt(listaTab.getValueAt(listaTab.getSelectedRow(),0).toString()));
                            setVisible(false);
                        }
                    }
                }
            });
        }
        
        buscarCam.getDocument().addDocumentListener(
            new DocumentListener() {
                public void changedUpdate(DocumentEvent e) {
                    filtrar();
                }
                public void insertUpdate(DocumentEvent e) {
                    filtrar();
                }
                public void removeUpdate(DocumentEvent e) {
                    filtrar();
                }
        });
        
 
        
        agregarBut.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                IAgregar iAgregar = new IAgregar(Productos.IPrincipal1.this);
            }
        } );
       
        Action actAgregar = new AbstractAction() {    
            public void actionPerformed(ActionEvent e) {
                agregarBut.doClick();
            }
        };
        
        agregarBut.getInputMap(agregarBut.WHEN_IN_FOCUSED_WINDOW).
                 put(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_MASK),"accion");
        agregarBut.getActionMap().put("accion", actAgregar);
        
        
        reabastecerBut.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(listaTab.getSelectedRowCount() > 0){
                    try {
                        new IEditar(IPrincipal1.this,CProducto.dameUno(Integer.parseInt(listaTab.getValueAt(listaTab.getSelectedRow(),0).toString())));
                    } catch (HeadlessException ex) {
                        Logger.getLogger(IPrincipal1.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ParseException ex) {
                        Logger.getLogger(IPrincipal1.class.getName()).log(Level.SEVERE, null, ex);
                    }catch (SQLException ex) {
                        Logger.getLogger(IPrincipal1.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(IPrincipal1.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                else{
                    JOptionPane.showMessageDialog(null,"Seleccione 1 producto!","Aviso",JOptionPane.WARNING_MESSAGE);    
                }
            }
        });
        
        editarBut.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                
                if(listaTab.getSelectedRowCount() > 0){
                    try {
                        new IEditar(IPrincipal1.this,CProducto.dameUno(Integer.parseInt(listaTab.getValueAt(listaTab.getSelectedRow(),0).toString())));
                    } catch (HeadlessException ex) {
                        Logger.getLogger(IPrincipal1.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ParseException ex) {
                        Logger.getLogger(IPrincipal1.class.getName()).log(Level.SEVERE, null, ex);
                    }catch (SQLException ex) {
                        Logger.getLogger(IPrincipal1.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(IPrincipal1.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                else{
                    JOptionPane.showMessageDialog(null,"Seleccione 1 producto!","Aviso",JOptionPane.WARNING_MESSAGE);    
                }
            }
        } );
        
        Action actEditar = new AbstractAction() {    
            public void actionPerformed(ActionEvent e) {
                editarBut.doClick();
            }
        };
        
        editarBut.getInputMap(editarBut.WHEN_IN_FOCUSED_WINDOW).
                 put(KeyStroke.getKeyStroke(KeyEvent.VK_D,InputEvent.CTRL_MASK),"accion");
        editarBut.getActionMap().put("accion", actEditar);
        
        eliminarBut.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                
                if(listaTab.getSelectedRowCount() > 0){
                    try {
                        int confirmado = JOptionPane.showConfirmDialog(null,"Seguro que desea eliminar " + listaTab.getValueAt(listaTab.getSelectedRow(),1).toString());

                        if (JOptionPane.OK_OPTION == confirmado){
                            boolean resultado = CProducto.eliminar(Integer.parseInt(listaTab.getValueAt(listaTab.getSelectedRow(),0).toString()));
                            if (resultado == false){
                            JOptionPane.showMessageDialog(null,"Producto eliminado correctamente!","Operación Exitosa!",JOptionPane.INFORMATION_MESSAGE);    
                                actualizar();
                            }
                        }
                    } catch (SQLException ex) {
                        Logger.getLogger(IPrincipal1.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(IPrincipal1.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                else{
                    JOptionPane.showMessageDialog(null,"Seleccione al menos 1 producto!","Aviso",JOptionPane.WARNING_MESSAGE);    
                }
                
            }
        });
        
        Action actEliminar = new AbstractAction() {    
            public void actionPerformed(ActionEvent e) {
                eliminarBut.doClick();
            }
        };
        
        eliminarBut.getInputMap(eliminarBut.WHEN_IN_FOCUSED_WINDOW).
                 put(KeyStroke.getKeyStroke(KeyEvent.VK_E,InputEvent.CTRL_MASK),"accion");
        eliminarBut.getActionMap().put("accion", actEliminar);
  
 
    }
    
    private void filtrar(){
        
        RowFilter<TableModel, Object> rf = null;
        try {
            rf = RowFilter.regexFilter(buscarCam.getText());
        } catch (java.util.regex.PatternSyntaxException e) {
            return;
        }
        clasificador.setRowFilter(rf);
    }
    
    public void actualizar() throws SQLException, ClassNotFoundException{
            
        Vector<String> columnNames = new Vector<String>(); columnNames.add("Código"); columnNames.add("N. Comercial"); columnNames.add("N. Genérico"); columnNames.add("Existencias"); columnNames.add("Presentación"); columnNames.add("Laboratorio");     
        Vector <Vector<String>> data = CProducto.dameTodo();

        DefaultTableModel modelo = new DefaultTableModel(data,columnNames){

            @Override
            public boolean isCellEditable (int row, int column)
            {
                return false;
            }
        };

        clasificador = new TableRowSorter<TableModel>(modelo);
        listaTab.setModel(modelo); listaTab.changeSelection(0,0,false,true); listaTab.setRowSorter(clasificador); listaTab.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
    }
    
    /*
     public static void main(String args[]){
       
         
          try{
              UIManager.setLookAndFeel(new SyntheticaWhiteVisionLookAndFeel());
        }catch (Exception e){ 
        }
         new IPrincipal1(null);
     }
     * */
}
